// server.js
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 3000;

app.use(cookieParser());
app.use(express.static('.'));

// 模拟用户数据库
const mockUsers = {
    'user1': { openid: 'mock_openid_1', nickname: '用户A', avatar: 'https://dummyimage.com/100x100/4CAF50/fff' },
    'user2': { openid: 'mock_openid_2', nickname: '用户B', avatar: 'https://dummyimage.com/100x100/2196F3/fff' }
};

// 生成模拟的code-to-user映射
const codeToUserMap = {};

// H5首页获取授权URL
app.get('/api/auth-url', (req, res) => {
    const redirectUri = `http://localhost:${port}/auth-callback`;
    const authUrl = `http://localhost:${port}/mock-wechat-auth?redirect_uri=${encodeURIComponent(redirectUri)}`;
    res.json({ authUrl });
});

// 模拟微信授权页
app.get('/mock-wechat-auth', (req, res) => {
    const { redirect_uri } = req.query;

    res.send(`
    <html>
      <head><title>模拟微信授权</title></head>
      <body>
        <h2>模拟微信授权页面</h2>
        ${Object.entries(mockUsers).map(([id, user]) => `
          <div style="margin: 20px; padding: 15px; border: 1px solid #ddd; display: flex; align-items: center;">
            <img src="${user.avatar}" width="50" height="50" style="border-radius: 50%; margin-right: 15px;">
            <div>
              <p style="margin: 0; font-weight: bold;">${user.nickname}</p>
              <button onclick="login('${id}')" style="margin-top: 10px; padding: 5px 10px; background: #07C160; color: white; border: none; border-radius: 3px;">授权登录</button>
            </div>
          </div>
        `).join('')}
        <script>
          function login(userId) {
            const code = 'mock_code_' + Math.random().toString(36).slice(2, 10);
            // 存储code-user映射（实际应该用数据库）
            fetch('/store-code-map', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ code, userId })
            }).then(() => {
              window.location.href = '${redirect_uri}?code=' + code + '&state=mock_state';
            });
          }
        </script>
      </body>
    </html>
  `);
});

// 存储code-user映射
app.post('/store-code-map', express.json(), (req, res) => {
    const { code, userId } = req.body;
    codeToUserMap[code] = userId;
    res.sendStatus(200);
});

// 授权回调处理
app.get('/auth-callback', (req, res) => {
    const { code } = req.query;

    if (!code || !codeToUserMap[code]) {
        return res.status(400).send('Invalid authorization code');
    }

    const userId = codeToUserMap[code];
    const userInfo = mockUsers[userId];

    // 跳转到H5中间页，携带用户信息
    const redirectUrl = `http://localhost:${port}/public/intermediate.html?` +
        `openid=${userInfo.openid}&` +
        `nickname=${encodeURIComponent(userInfo.nickname)}&` +
        `avatar=${encodeURIComponent(userInfo.avatar)}`;

    res.redirect(redirectUrl);
});

// 获取用户信息API
app.get('/api/user-info', (req, res) => {
    const { openid } = req.cookies;
    if (!openid) return res.status(401).json({ error: '未登录' });

    const user = Object.values(mockUsers).find(u => u.openid === openid);
    if (!user) return res.status(404).json({ error: '用户不存在' });

    res.json(user);
});

// 退出登录API
app.get('/api/logout', (req, res) => {
    res.clearCookie('openid');
    res.clearCookie('nickname');
    res.clearCookie('avatar');
    res.json({ message: '已退出登录' });
});

app.listen(port, () => {
    console.log(`服务运行在 http://localhost:${port}`);
});